package cn.lxh.config;

import org.apache.rocketmq.client.consumer.DefaultMQPullConsumer;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.common.protocol.heartbeat.MessageModel;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class MQConfig {

    @Value("${rocketmq.name-server}") // MQ地址
    private String nameServerAddr;

    @Value("${spring.application.name}") // 服务名
    private String applicationName;

    // RocketMQ手动拉取消息
    @Bean
    public DefaultMQPullConsumer pullConsumer() {
        // 创建消费者 (pull模式)
        DefaultMQPullConsumer consumer = new DefaultMQPullConsumer(applicationName + "-consumer");
        // 指定MQ地址
        consumer.setNamesrvAddr(nameServerAddr);
        try {
            // 指定消费模式 (集群 (一个消息只能被一个消费者消费), 广播 (一个消息可以被多个消费者消费), 这里指定集群模式)
            consumer.setMessageModel(MessageModel.CLUSTERING);
            consumer.start();
            return consumer;
        } catch (MQClientException e) {
            throw new RuntimeException(e);
        }
    }
}